package com.randomrpg.game

import java.util.Random
import Math._

/**
 * Represents a player in the game
 */
@serializable @SerialVersionUID(666)
class Player(val clazz: RPGClass, val name: String) extends GameEntity(1, clazz.life) {
  
  private val rand = new Random
  
  val attributes = clazz.attributes
  var exp = 0
  var maxMp = clazz.mp
  var mp = maxMp
  
  def str = attributes.str
  def dex = attributes.dex
  def con = attributes.con
  def int = attributes.int
  def will = attributes.will
  
  def str_=(value: Int) = attributes.str = value
  def dex_=(value: Int) = attributes.dex = value
  def con_=(value: Int) = attributes.con = value
  def int_=(value: Int) = attributes.int = value
  def will_=(value: Int) = attributes.will = value
  
  def critical = attributes.dex * 2
  def evade = attributes.dex
  
  def baseDamage = str until str + max((level / 2), 1) + 1
  
  def damage = rand.nextInt(baseDamage.last - baseDamage.first + 1) + baseDamage.first
  
  def attack(enemy: Player): (Int, Boolean) = {
    // calculate critical
    var percent = rand.nextInt(100)
    var damagee = 0
    var crit = false
    if(percent < critical) { damagee = damage * 2; crit = true }
    else damagee = damage
    
    // calculate evade
    percent = rand.nextInt(100)
    if(percent < enemy.evade) damagee = -1
    else enemy.life -= damagee
    (damagee, crit)
  }
  
  def checkLevelUp: Boolean = {
    if(level < 20 && XPTable.leveled(level, exp)) {
      clazz.levelUp(this)
      return true
    }
    false
  }
  
  def canCast = mp > Magics.magicCost
  
  def lowLife = life < (maxLife / 2)
  
  def isCaster = clazz.isInstanceOf[Mage] || clazz.isInstanceOf[Cleric]
  
  def incLife = if(life < maxLife) life += min(level, maxLife - life)
  
  def incMp = if(mp < maxMp) mp += min(level, maxMp - life)
  
  override def toString: String = {
    val builder = new StringBuilder
    builder.append(name)
    builder.append("\n\t class: " + clazz.name + " " + level)
    builder.append("\n\t life: " + life + "/" + maxLife)
    builder.append("\n\t - str: " + str)
    builder.append("\n\t - dex: " + dex)
    builder.append("\n\t - con: " + con)
    builder.append("\n\t - int: " + int)
    builder.append("\n\t - will: " + will)
    builder.append("\n\t damage: " + baseDamage.first + "-" + baseDamage.last)
    builder.append("\n\t critical: " + critical + "%")
    builder.append("\n\t evade: " + evade + "%")
    if(isCaster) builder.append("\n\t MP: " + mp + "/" + maxMp)
    builder.append("\n\t XP: " + exp + " (next level: " + XPTable.toNextlevel(level) + ")")
    builder.toString()
  }
}